import React, { PureComponent } from 'react'
import { connect } from 'dva'
import {
  Card,
  Form,
  Input,
  Table,
  Row,
  Col,
  Button,
  Select,
  notification,
  Alert,
  Popconfirm,
  Divider,
} from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import router from 'umi/router'
import PropModal from './PropModal'
import styles from './Index.less'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item
const { Option } = Select

@connect(({ loading, propCheck }) => ({
  propCheck,
  loading: loading.models.propCheck,
}))
@Form.create()
export default class propCheck extends PureComponent {
  // 组件加载完成后加载数据
  componentDidMount() {
    const { dispatch } = this.props
    dispatch({
      type: 'propCheck/fetchList',
    })

    dispatch({
      type: 'propCheck/fetchSelectPropData',
      payload: {
        type: 'pd_status',
      },
    })
  }

  handleAdd = () => {
    // 清空currentItem
    this.props.dispatch({
      type: 'propCheck/updateState',
      payload: {
        currentItem: {},
      },
    })
    router.push('/property/checkupdate')
  }

  // 清除选择
  cleanSelectedKeys = () => {
    this.handleSelectRows([])
  }

  // 行选事件
  handleSelectRows = rows => {
    const { dispatch } = this.props
    dispatch({
      type: 'propCheck/updateState',
      payload: {
        selectedRowKeys: rows,
      },
    })
  }

  // 编辑
  handleEditClick = async record => {
    if (record.id) {
      try {
        await this.props.dispatch({
          type: 'propCheck/edit',
          payload: {
            id: record.id,
          },
        })

        router.push('/property/checkupdate')
      } catch (error) {
        console.log(error)
      }
    } else {
      notification.error('没有选择记录')
    }
  }

  // 重置事件
  handleFormReset = () => {
    const { form, dispatch } = this.props
    form.resetFields()
    dispatch({
      type: 'propCheck/fetchList',
    })
  }

  // 搜索事件
  handleSearch = e => {
    e.preventDefault()

    const { form, dispatch } = this.props
    // 表单验证
    form.validateFields((err, fieldsValue) => {
      if (err) return

      const values = {
        ...fieldsValue,
      }

      dispatch({
        type: 'propCheck/fetchList',
        payload: values,
      })
    })
  }

  handleDelete = e => {
    e.preventDefault()
    const { selectedRowKeys } = this.props.propCheck
    const { dispatch } = this.props
    dispatch({
      type: 'propCheck/remove',
      payload: {
        ids: selectedRowKeys,
      },
    })
  }

  // 表格动作触发事件
  handleListChange = (pg, filtersArg, sorter) => {
    const { dispatch } = this.props
    const { formValues, pagination } = this.props.propCheck
    if (sorter.field && pagination.currentPage === pg.current) {
      return
    }

    const params = {
      ...formValues,
      current: pg.current,
    }

    dispatch({
      type: 'propCheck/fetchList',
      payload: params,
    })
  }

  handleShowPropsModal = (record, e) => {
    const { dispatch } = this.props
    e.preventDefault()
    //
    dispatch({
      type: 'propCheck/updateState',
      payload: {
        showProps: true,
      },
    })
    //
    dispatch({
      type: 'propCheck/fetchProps',
      payload: {
        id: record.id,
      },
    })
  }

  // 资产属性下拉option
  renderOptionNodes(type) {
    const data = this.props.propCheck[type]
    return data.map(item => (
      <Option key={item.id} value={item.keyName}>
        {item.keyValue}
      </Option>
    ))
  }

  renderSearchForm = () => {
    const { loading } = this.props
    //
    const { getFieldDecorator } = this.props.form
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="*盘点单号">
              {getFieldDecorator('orderNo')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="盘点状态">
              {getFieldDecorator('orderStatus')(
                <Select placeholder="请选择" allowClear>
                  {this.renderOptionNodes('pd_status')}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="*盘点负责人">
              {getFieldDecorator('pdOperatorName')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 15 }}>
          <div style={{ marginLeft: 'auto' }}>
            <Button type="primary" htmlType="submit" loading={loading}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} loading={loading}>
              重置
            </Button>
          </div>
        </div>
      </Form>
    )
  }

  // 渲染界面
  render() {
    const { loading, dispatch } = this.props
    const { list, pagination, showProps, PropsData, selectedRowKeys } = this.props.propCheck

    const rowSelectionProps = {
      selectedRowKeys,
      onChange: selectedKeys => {
        this.handleSelectRows(selectedKeys)
      },
    }

    const propModalProps = {
      showModal: showProps,
      dataSource: PropsData,
      modalCloseCallback: () => {
        dispatch({
          type: 'propCheck/updateState',
          payload: {
            showProps: false,
          },
        })
      },
    }

    const columns = [
      {
        render: (t, r, i) => <span>{i + 1}</span>,
        width: 35,
        key: 'index',
      },
      {
        title: '盘点单号',
        align: 'center',
        dataIndex: 'orderNo',
        width: 200,
        sorter: (a, b) => a.orderNo && a.orderNo.localeCompare(b.orderNo),
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '盘点单名称',
        align: 'center',
        dataIndex: 'pdJobName',
        width: 80,
      },
      {
        title: '盘点负责人',
        align: 'center',
        dataIndex: 'pdOperatorName',
        width: 80,
      },
      {
        title: '开始时间',
        align: 'center',
        dataIndex: 'pdStartDate',
        width: 100,
      },
      {
        title: '结束时间',
        align: 'center',
        dataIndex: 'pdEndDate',
        width: 100,
      },
      {
        title: '状态',
        align: 'center',
        dataIndex: 'statusStr',
        width: 80,
      },
      {
        title: '操作',
        align: 'center',
        width: 80,
        render: (text, record) => (
          <div>
            <a onClick={e => this.handleShowPropsModal(record, e)}>查看</a>
            {record.orderStatus === '0001' ? (
              <React.Fragment>
                <Divider type="vertical" />
                <a onClick={e => this.handleEditClick(record, e)}>修改</a>
              </React.Fragment>
            ) : null}
          </div>
        ),
      },
    ]
    return (
      <PageHeaderWrapper title="资产盘点">
        <div className={styles.goodsInfoList}>
          <div className={styles.goodsInfoListForm}>
            <Card className={styles.noPadding} bordered={false}>
              {this.renderSearchForm()}
            </Card>
            <Card style={{ marginTop: 15 }} className={styles.noPadding} bordered={false}>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  paddingTop: 15,
                  paddingBottom: 15,
                  backgroundColor: '#fff',
                }}
              >
                <div className={styles.tableTopbtns}>
                  <Button icon="plus" type="primary" loading={loading} onClick={this.handleAdd}>
                    新增盘点单
                  </Button>
                  <Popconfirm
                    title="确定要删除吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={e => this.handleDelete(e)}
                  >
                    <Button type="danger" loading={loading} style={{ marginLeft: 8 }}>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              </div>
              <Alert
                style={{ marginBottom: 8 }}
                message={
                  <div>
                    已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a>{' '}
                    项&nbsp;&nbsp;
                    <a style={{ marginLeft: 24 }} onClick={() => this.handleSelectRows([])}>
                      清空选择
                    </a>
                  </div>
                }
                type="info"
                showIcon
              />
              <Table
                loading={loading}
                size="small"
                bordered
                dataSource={list}
                rowKey={record => record.id}
                pagination={pagination}
                columns={columns}
                onChange={this.handleListChange}
                rowSelection={rowSelectionProps}
              />
            </Card>
          </div>
        </div>
        <PropModal {...propModalProps}></PropModal>
      </PageHeaderWrapper>
    )
  }
}
